<?php
/**
 * Author: Nguyen Hoai Tan (nguoiao007@gmail.com)
 * 
 * @category   default 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 * 
 */
require_once 'modules/user/models/User.php';
require_once 'modules/user/models/Group.php';

class user_IndexController extends Nine_Controller_Action
{
	
	public function newAction(){
		
		if (false == $this->checkPermission('new_user')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
		
		$this->view->headTitle('New User');
		$this->view->menuId = array('setup','user');
		
//		$id = $this->_getParam('id', false);
		$data = $this->_getParam('data', false);
		
//		$objGroup = new Models_Group();
		$objUser = new Models_User();
		
		$errors = array();
		if(false != $data){
//			$data['shop_id'] = Nine_Registry::getSession()->currentShop;
//			$data['branch_id'] = Nine_Registry::getSession()->currentBranch;
//			$data['created_date'] = time();
//			$data['enabled'] = 1;
//			if($data['password'] != ""){
//				$data['password'] = md5($data['password']);
//			}else {
//				unset($data['password']);
//			}
//			$data['full_name'] = $data['first_name'] . " " . $data['last_name'];
//			$objUser->insert($data);
//			$this->session->insertUser = "Insert Success";
//			$this->_redirect('user/index/manage');

		 	$newUser = array(
                            'group_id'        => 3,
            				'shop_id'		  => @$this->session->currentShop,
		 					'branch_id'		  => @$this->session->currentBranch,
                            'username'        => @$data['email'],
                            'email'           => @$data['email'],
		 					'first_name'	  => @$data['first_name'],
		 					'last_name'	  	  => @$data['last_name'],
                            'full_name'       => @trim($data['first_name'] . ' ' . $data['last_name']),
                            'password'        => $data['password'],
                            'created_date'    => time(),
                            'enabled'         => 1
                        );
                        
           $exclude = array('username','password');
		   $errors = $objUser->validate($newUser, $exclude);
            
           if (true === $errors) {
                $newUser['password'] = md5($newUser['password']);
           		try {
                    $id = $objUser->insert($newUser);
                    $this->session->userMessage =  array(
                       'success' => true,
                       'message' => Nine_Language::translate('User is created successfully.')
                    );
                    $this->_redirect('user/index/manage');
                } catch (Exception $e) {
                    $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
                }
           }
		}
//		$allGroup = $objGroup->getAll()->toArray();
		
		/**
		 * Assign to view
		 */
//		$this->view->group = $allGroup;
		$this->view->errors = $errors;
        $this->view->data = $data;
	}
	
	public function editAction(){
		
		if (false == $this->checkPermission('edit_user')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
		
		$this->view->headTitle('Edit User');
		$this->view->menuId = array('setup','user');
		$id = $this->_getParam('id', false);
		$data = $this->_getParam('data', false);
		
		if (false == $id) {
            $this->_redirect('user/index/manage');
        }
		
		$objGroup = new Models_Group();
		$objUser = new Models_User();
		
		/**
		 * Get old data
		 */
	 	$oldUser = $objUser->getUser($id)->toArray();
    
        if (empty($oldUser)) {
            /**
             * User doesn't exsit
             */
            
            $this->session->userMessage = array(
                                           'success' => false,
                                           'message' => Nine_Language::translate('User does NOT exist')
                                       );
            $this->_redirect('user/index/manage');
        }
		
		$errors = array();
		if(false != $data){
//			if($data['password'] != ""){
//				$data['password'] = md5($data['password']);
//			}else {
//				unset($data['password']);
//			}
//			$data['full_name'] = $data['first_name'] . " " . $data['last_name'];
//			$objUser->update($data,array("user_id = ? " =>$id));
//			$this->session->updateUser = "Update Success";
//			$this->_redirect('user/index/manage');

			$newUser = array(
                            'username'        => @$data['email'],
                            'email'           => @$data['email'],
							'first_name'	  => @$data['first_name'],
		 					'last_name'	  	  => @$data['last_name'],
                            'full_name'       => @trim($data['first_name'] . ' ' . $data['last_name']),
                            'password'        => $data['password']
                        );
			$exclude = array('username','password');
			if (null == @$newUser['password']) {
                unset($newUser['password']);
            }
            if ($newUser['email'] == $oldUser['email'] || null == @$newUser['email']) {
                $exclude[] = 'email';
                unset($newUser['email']);
            }
            
            $errors = $objUser->validate($newUser, $exclude);
            
            if (true === $errors) {
             	if (null != @$newUser['password']) {
                    $newUser['password'] = md5($newUser['password']);
                }
                try {
	                if (! empty($newUser)) {
	                 	$objUser->update($newUser, array('user_id=?' => $id));
	                	/**
	                     * Reload current login user
	                     */
	                     if ( $oldUser['user_id'] == Nine_Registry::getLoggedInUserId() && null != $newUser['username']) {
	                        	/**
	                        	 * I am logging in, I changed to new username
	                        	 */
	                        	Nine_Registry::getAuth()->loginAuto($newUser['username']);
	                     }
	                }
	                $this->session->userMessage = array(
	                                           'success' => true,
	                                           'message' => Nine_Language::translate('User is updated successfully')
	                                   );
	                $this->_redirect('user/index/manage');
                } catch(Exception $e) {
                	$errors = array('main' => Nine_Language::translate('Can not update user now'));
                }
            }
			
		}
		else {
			$data = $oldUser;
		}
//		$allGroup = $objGroup->getAll()->toArray();
		
//		$user = $objUser->getUser($id);
//		$this->view->group = $allGroup;
//		$this->view->user = $user;

		
		/**
		 * Assign to view
		 */
		$this->view->errors = $errors;
        $this->view->data = $data;
	}
	public function manageAction(){
		
		if (false == $this->checkPermission('see_user')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
		
		
		$this->view->headTitle('Manger User');
		$this->view->menuId = array('setup','user');
		$objUser = new Models_User();
		$condition = array();
		$config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",false);
		$data = $this->_getParam('condition', false);
    	
		if(false == $currentPage){
        	unset($this->session->con);
        	$currentPage = 1;
        }
        if (false === $data) {
            $condition = $this->session->con;
        } else {
        	$condition['full_name'] = $data;
            $this->session->con = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
		$displayNum = $this->_getParam('displayNum', false);
		/**
         * Get number of customer per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->customerDisplayNum;
        } else {
            $this->session->customerDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
		$allUser = $objUser->getAllUsersWithShopPage(Nine_Registry::getSession()->currentShop,$condition,$numRowPerPage,($currentPage - 1) * $numRowPerPage);
		$count = count($objUser->getAllUsersWithShopPage(Nine_Registry::getSession()->currentShop,$condition));
		foreach ($allUser as &$item){
			$item['day'] = date('d/m/Y',$item['created_date']);
		}
		unset($item);
		$this->setPagination($numRowPerPage, $currentPage, $count);
		$this->view->allUser = $allUser;
//		if($this->session->insertUser != null){
//			$this->view->messInsert = $this->session->insertUser;
//			$this->session->insertUser = null;
//		}
//		if($this->session->updateUser != null){
//			$this->view->messUpdate = $this->session->updateUser;
//			$this->session->updateUser = null;
//		}

		$this->view->userMessage = $this->session->userMessage;
		$this->session->userMessage = null;
	}
	
//    /**
//     * Forgot Username or Password
//     */
//	public function forgotUsernameOrPasswordAction()
//    {
//        $this->view->headTitle('Forgot username or password');
//        $this->view->bannerImage = 12;
//        $this->view->menuId = 'assistance';
//        
//        $objContent = new Models_Content();
//        $objUser = new Models_User();
//        
//        /**
//         * Get email param
//         */
//        $email = $this->_getParam('email', false);
//        
//        if (false != $email) {
//            $user = @reset($objUser->getByColumns(array('email=?'=>$email))->toArray());
//            
//            if (false == $user) {
//                 $this->session->forgotMessage = array(
//                								'success'	=>	false,
//                								'message'	=>	Nine_Language::translate("Email doesn't exist. Please try with correct email.")
//                							);
//            } else {
//                /**
//                 * Create random code
//                 */
//                $randomCode = $objUser->generateActiveCode(20);
//                $link = Nine_Registry::getConfig('liveSite'). 'access/index/login/username/' . $user['username'] . '/password/' . $randomCode;
//                /**
//                 * Update user
//                 */
//                $data = array(
//                    'forgot_password_code' => md5($randomCode),
//                    'forgot_password_expired_date' => time() + Nine_Registry::getConfig('forgotPasswordExpiredTime')
//                );
//                
//                $objUser->update($data, array('user_id=?' => $user['user_id']));
//			
//                /**
//                 * Send mail
//                 */
//                $data = array(
//                        'email' => $email,
//                        'link' => $link,
//                		'new_password'	=>	$randomCode,
//                        'username' => $user['username'],
//                        'full_name' => $user['full_name']
//                );
//                $objMail = new Models_Mail();
//                $objMail->sendHtmlMail('forgot_password', $data, $email);
//                
//                $this->session->forgotMessage = array(
//                								'success'	=>	true,
//                								'message'	=>	Nine_Language::translate("Please check your email to see your username and new password. Please note that new password is only valid in 24 hours. You can still use old password if you don't use new password.")
//                							);
//        	}
//    	}
//    	
//        /**
//         * Get content
//         */
//        $contentLeft = @$objContent->getContentByGid(57)->toArray();
//        $tmp = explode("||", $contentLeft['images']);
//        $contentLeft['main_image'] = Nine_Function::getThumbImage(@$tmp[0],207,143);
//        
//        $contentCenter = @$objContent->getContentByGid(55)->toArray();
//        
//        $this->view->contentLeft = $contentLeft;
//        $this->view->contentCenter = $contentCenter;
//    	
//	    $this->view->email = $email;
//	    
//	    $this->view->forgotMessage = $this->session->forgotMessage;
//	    $this->session->forgotMessage = null;    
//	        
//    }
}